#include"UdpServer.hpp"
#include<memory>
#include<vector>

void Usage(std::string proc)
{
    std::cout<<"\nUsage:"<<proc<<"port[1024+]\n"<<std::endl;
}
//将对数据的处理提取出来，实质是对我们的代码实现分层
std::string Handler(const std::string& info,const std::string& client_ip,uint16_t client_port)
{
    std::cout<<"["<<client_ip<<":"<<client_port<<"]#"<<info<<std::endl;
    std::string res="Server get a messege: ";//对数据的简单处理
    res+=info;
    std::cout<<res<<std::endl;

    // pid_t id=fork();
    // if(id==0)
    // {
    //     //子进程
    //     //ls -a -l ——> "ls" "-a" "-l"
    //     //exec*();
    // }

    return res;
}

bool SafeCheck(const std::string& cmd)
{
    std::vector<std::string> key_word={"rm","mv","cp","kill","sudo","unlink","uninstall","yum"};
    for(auto& word:key_word)
    {
        auto pos=cmd.find(word);
        if(pos!=std::string::npos) return false;
    }
    return true;
}

std::string ExcuteCommand(const std::string& cmd)
{
    if(!SafeCheck(cmd))return "banned dir!";

    FILE* fp=popen(cmd.c_str(),"r");//popen是系统调用接口，它可以接收字符串类型的命令，在底层fork，让父子进程建立管道，让子进程的运行结果返回给调用方
    if(nullptr==fp)
    {
        perror("popen");
        return "error";
    }
    std::string res;
    char buffer[4096];
    while(true)
    {
        char* ret=fgets(buffer,sizeof(buffer),fp);
        if(ret==nullptr) break;
        res+=buffer;
    }

    pclose(fp);
    return res;
}

//./udp_server port
int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t port=std::stoi(argv[1]);

    std::unique_ptr<UdpServer> svr(new UdpServer(port));

    svr->Init();//服务器初始化
    svr->Run(Handler);//运行服务器

    return 0;
}